# @author: Samuel Taylor <samtaylor.uk@gmail.com>
# @package: winecellar
# @license: GNU GPLv3
#
# Copyright (C) 2010  Samuel Taylor <samtaylor.uk@gmail.com>
#----------------------------------------------------------------------
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program.  If not, see <http://www.gnu.org/licenses/>.
#-----------------------------------------------------------------------

__author__ = 'Samuel Taylor <samtaylor.uk@gmail.com>'

import os
import sys
import tarfile
from lxml import etree
from WineCellar.Preferences import Preferences
import uuid
import WineCellar.Config
import urllib
import urlparse
import random
import time
from WineCellar.Download import Download
from WineCellar.Logger import logger
import WineCellar.helpers

class RepositoryManager:
    """
    This class manages repositories
    """
    def update(self, fileUpdateHook = None, downloadUpdateHook = None):
        self.Preferences = Preferences()
        repositories = self.Preferences.getRepositories()
        
        update = {}
        i = 1 
        for key, repository in repositories.iteritems():
            if repository["id"] == None:
                repository["id"] = str(uuid.uuid1())
                try:
                    update[hash(repository["url"])]["id"] = repository["id"]
                except:
                    update[hash(repository["url"])] = {}
                    update[hash(repository["url"])]["id"] = repository["id"]
                
            if not os.path.exists(str(WineCellar.Config.__repositoriesPath__ + repository["id"])):
                os.makedirs(str(WineCellar.Config.__repositoriesPath__ + repository["id"]))
            
            if not os.path.exists(str(WineCellar.Config.__repositoriesPath__ + repository["id"] + "/icons")):
                os.makedirs(str(WineCellar.Config.__repositoriesPath__ + repository["id"] + "/icons"))
            
            #TODO: Something better for download
            if not fileUpdateHook == None:
                fileUpdateHook(i, len(repositories))
            
            Download(repository["url"]+"/index.xml", str(WineCellar.Config.__repositoriesPath__ + repository["id"]+"/"), downloadUpdateHook)
            
            i += 1
            
            parser = etree.XMLParser(remove_blank_text=True)
            self.tree = etree.parse(str(WineCellar.Config.__repositoriesPath__ + repository["id"]+"/index.xml"), parser)
            
            for element in self.tree.iter("icon"):
                Download(repository["url"]+"/icons/"+element.text, str(WineCellar.Config.__repositoriesPath__ + repository["id"]+"/icons/"), downloadUpdateHook)
                
            if repository["name"] == None:
                repository["name"] = self.tree.find("name").text
                try:
                    update[hash(repository["url"])]["name"] = repository["name"]
                except:
                    update[hash(repository["url"])] = {}
                    update[hash(repository["url"])]["name"] = repository["name"]

        if update:
            parser = etree.XMLParser(remove_blank_text=True)
            tree = etree.parse(str(WineCellar.Config.__configpath__), parser)

            for element in tree.iter("repository"):
                if update[hash(element.text)]["id"] != None:
                    element.attrib['id'] = update[hash(element.text)]["id"]
                    
                if update[hash(element.text)]["name"] != None:
                    element.attrib['name'] = update[hash(element.text)]["name"]
                
                f = open(str(Config.__configpath__), 'w')
                f.write(etree.tostring(tree, pretty_print=True, encoding='iso-8859-1'))
                f.close()
    
    def findApplication(self, shortname):
        packages = {}
        if os.path.exists(str(WineCellar.Config.__repositoriesPath__)):
            for file in os.listdir(str(WineCellar.Config.__repositoriesPath__)):
                dirfile = os.path.join(str(WineCellar.Config.__repositoriesPath__), file)
                if os.path.isdir(dirfile):
                    parser = etree.XMLParser(remove_blank_text=True)
                    tree = etree.parse(str(dirfile +'/index.xml'), parser)
                    i = 0
                    
                    rName = tree.find("name").text
                    
                    for element in tree.iter("Application"):
                        if element.find("shortname").text == shortname:
                            for package in element.iter("package"):
                                packages[i]={"name": element.find("name").text, "vendor": element.find("vendor").text, "repository": rName, "repositoryID": file, "version": package.attrib['version'], "url": self.getMirror(file)+"/"+package.text, "package": package.text, "path": str(WineCellar.Config.__repositoriesPath__ +file+"/"+package.text)}
                                i += 1
        if packages:
            return packages
        else:
            return False

    def getMirror(self, repositoryID):
        parser = etree.XMLParser(remove_blank_text=True)
        tree = etree.parse(str(WineCellar.Config.__repositoriesPath__+repositoryID+"/index.xml"), parser)
        i = 0
        mirrors = {}
        
        for element in tree.iter("mirror"):
            mirrors[i] = element.text
            i += 1
        
        return mirrors[random.randrange(0, i, 1)]

    def getPackages(self, cat=None):
        """Returns array of packages with descriptions
        that are in the repositories"""
        packages = {}
        if os.path.exists(str(WineCellar.Config.__repositoriesPath__)):
            for file in os.listdir(str(WineCellar.Config.__repositoriesPath__)):
                dirfile = os.path.join(str(WineCellar.Config.__repositoriesPath__), file)
                
                if os.path.isdir(dirfile):
                    parser = etree.XMLParser(remove_blank_text=True)
                    tree = etree.parse(str(dirfile +'/index.xml'), parser)
                    
                    i = 0
                    for element in tree.iter("Application"):
                        if element.find("category").text == cat or cat == None or cat == "All":
                            packages[i] = [element.find("shortname").text, dirfile + "/icons/" + element.find("icon").text, element.find("name").text, element.find("description").text]
                        i += 1
        
        return packages
        
    def getCategories(self):
        """Returns array of categories
        that are in the repositories"""
        categories = []
        if os.path.exists(str(WineCellar.Config.__repositoriesPath__)):
            for file in os.listdir(str(WineCellar.Config.__repositoriesPath__)):
                dirfile = os.path.join(str(WineCellar.Config.__repositoriesPath__), file)
                
                if os.path.isdir(dirfile):
                    parser = etree.XMLParser(remove_blank_text=True)
                    tree = etree.parse(str(dirfile +'/index.xml'), parser)
                    
                    i = 0
                    for element in tree.iter("Application"):
                        categories.append(element.find("category").text)
                        i += 1
        
        categories = WineCellar.helpers.uniqifyList(categories)
        return categories
        
    def downloadPackage(self, url, filename, repositoryID, downloadUpdateHook):
        if os.path.exists(str(WineCellar.Config.__repositoriesPath__ + repositoryID+"/"+filename)):
            return True
        else:
            try:
                logger.debug("Downloading package: "+url)
                Download(url, str(WineCellar.Config.__repositoriesPath__ + repositoryID+"/"), downloadUpdateHook)
                return True
            except:
                return False

